package track1;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;

public class TrackReflectDemo1 {
    public static void main(String[] args) throws IllegalAccessException, IOException {
        Student s =new Student("a",13,'女',167.2,"睡觉");
        Teacher teacher = new Teacher("hanser", 10000);
        saveObject(s);
    }

    //把对象里面所有的成员变量名和值保存到本地文件中
    public static void saveObject(Object object) throws IllegalAccessException, IOException {
        //获取字节码文件对象
        Class c = object.getClass();

        //创建io流
        BufferedWriter bw = new BufferedWriter(new FileWriter("reflect\\src\\a.txt"));


        //获取所有的成员变量
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            //获取成员变量的名字
            String name = field.getName();
            //获取成员变量的值
            Object value = field.get(object);
            System.out.println(name+"="+value);
            //写入数据
            bw.write(name+"="+value);
            bw.newLine();
        }
        bw.close();
    }
}
